/*
 *     Prionace - A file navigator to manage your files
 *
 *     Copyright (C) 2012 Francivan Bezerra
 *
 *     This file is part of Prionace.
 *
 *     Prionace is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Prionace is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Prionace.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.fba.prionace.process;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

import org.fba.prionace.config.ProcessMapStorage;
import org.fba.prionace.file.JFile;

public class ExecProcess {

	private static ExecProcess instance;

	ExecProcessMap processMap;

	private ExecProcess() throws IOException {
		processMap = ProcessMapStorage.restore();

		if (processMap == null) {
			processMap = new ExecProcessMap();
		}
	}

	public static ExecProcess getInstance() throws IOException {
		if (instance == null) {
			instance = new ExecProcess();
		}

		return instance;
	}

	public void addExecProcess(File file, String exec)
			throws FileNotFoundException {
		String mimeType = getMimeType(file);
		processMap.addExecProcess(mimeType, exec);
		ProcessMapStorage.save(processMap);
	}

	public void open(File file) throws IOException {
		String mimeType = getMimeType(file);
		String[] cmd = processMap.getExecParam(mimeType);
		String[] cmdOpen;

		if (cmd == null) {
			throw new FileNotFoundException(
					"No executable associated to this type of file");
		}

		cmdOpen = Arrays.copyOf(cmd, cmd.length + 1);
		cmdOpen[cmdOpen.length - 1] = file.getAbsolutePath();

		Runtime runtime = Runtime.getRuntime();
		runtime.exec(cmdOpen, null, file.getParentFile());
	}

	private String getMimeType(File file) {
		JFile type = new JFile();
		type.setFile(file);
		return type.getMimeType();
	}
}
